/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mvp.levelup.annotations;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author WORKSPOT2
 */
public class CsvMechanism<T>
{

    private List<Field> annotatedFields;

    public CsvMechanism(Class<T> objClass)
    {
        annotatedFields = new ArrayList<Field>();
        Field[] fields = objClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++)
        {
            if (fields[i].getAnnotation(Csv.class) != null)
            {
                fields[i].setAccessible(true);
                annotatedFields.add(fields[i]);
            }
        }
        if (annotatedFields.isEmpty())
        {
            throw new IllegalArgumentException("No Csv annotated fields!");
        }
    }

    public String convertToCsv(List<T> objects)
    {
        try
        {
            StringBuilder stringBuilder = new StringBuilder();
            Iterator<Field> iter = annotatedFields.iterator();
            Field tmpField;
            while (iter.hasNext())
            {
                tmpField = iter.next();
                stringBuilder.append(tmpField.getName()).append(";");
            }
            stringBuilder.append("\n");
            Iterator<T> objIter = objects.iterator();
            T tmpObj;
            Object tmpValue;
            while (objIter.hasNext())
            {
                tmpObj = objIter.next();
                iter = annotatedFields.iterator();
                while (iter.hasNext())
                {
                    tmpField = iter.next();
                    tmpValue = tmpField.get(tmpObj);
                    stringBuilder.append(tmpValue.toString()).append(";");
                }
                stringBuilder.append("\n");
            }
            return stringBuilder.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "";

        }

    }
}
